package com.bawei.live.viewmodel

import androidx.lifecycle.viewModelScope
import com.bawei.common.mvi.BaseViewModel
import com.bawei.live.LiveUiState
import com.bawei.live.LiveViewIntent
import com.bawei.live.repos.LiveRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class LiveViewModel @Inject constructor(private val repository: LiveRepository) :
    BaseViewModel<LiveViewIntent>() {
    private val _uiState = MutableStateFlow<LiveUiState>(LiveUiState.LoadEmpty)
    val uiState: StateFlow<LiveUiState> = _uiState

    override fun handIntent(uiIntent: LiveViewIntent) {
        when (uiIntent) {
            is LiveViewIntent.LoadRecommendSimpleVideo -> loadRecommendSimpleVideo(uiIntent.page, uiIntent.pageSize)
        }
    }

    private fun loadRecommendSimpleVideo(page: Int, pageSize: Int) {
        viewModelScope.launch {
            try {
                _uiState.value = LiveUiState.LoadEmpty
                val result = repository.getRecommendVideo(page, pageSize)
                if (result.code == 0 && result.data.isNotEmpty()) {
                    _uiState.value = LiveUiState.LoadSimpleVideoSuccess(result.data)
                } else {
                    _uiState.value = LiveUiState.LoadSimpleVideoFail(result.msg)
                }
            } catch (e: Exception) {
                _uiState.value = LiveUiState.LoadSimpleVideoFail("加载数据异常！")
            }
        }
    }

}